<template>
  <div class="page-wrap">
    <div class="top-wrap">
      机台
      <el-select style="width: 80px; margin: 0 6px" v-model="mid" placeholder="请选择" @change="handleSelectChange">
        <el-option
          v-for="item in [{ label: '0000000000000000', value: '0000000000000000' }]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      锭号
      <el-input type="text" v-model="spinNum" style="width: 100px"></el-input>
      日期
      <el-date-picker v-model="currentRow" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="margin: 0 6px 0 0" />
      <!-- <el-select style="width: 80px; margin: 0 6px" v-model="spinNum" placeholder="请选择" @change="handleSelectChange">
        <el-option v-for="item in spinlist" :key="item.value" :label="item.label" :value="item.value" />
      </el-select> -->
      异常类型
      <el-select style="width: 100px; margin: 0 6px" v-model="except" placeholder="请选择" @change="handleSelectChange">
        <el-option v-for="item in exceptChr" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <!-- 时间段
      <el-date-picker
        style="width: 160px; margin: 0 6px"
        v-model="timeRange"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        align="right"
      /> -->

      <el-button @click="handleSearchBtnClick" slot="append" icon="el-icon-search"> 检索</el-button>
    </div>
    <div class="spin-status">
      <div class="spin-status-inner">
        <el-table size="mini" border :data="leftData" height="calc(100% - 30px)" style="width: calc(100% - 10px)">
          <el-table-column prop="PAGE_ROW_NUMBER" label="左" width="60" align="center" />
          <!-- <el-table-column prop="mid" label="机台编号" width="150" /> -->
          <el-table-column prop="inx" label="锭号" width="50" align="center">
            <template slot-scope="scope"> {{ scope.row.inx + 1 }} </template>
          </el-table-column>
          <el-table-column prop="type" label="异常" width="150" align="center">
            <!-- <template slot-scope="scope"> {{ exceptChr[scope.row.type - 1].label }} </template> -->
          </el-table-column>

          <el-table-column prop="startTime" label="起始时间" width="106">
            <template slot-scope="scope"> {{ scope.row.startTime | toTime }}</template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="106">
            <template slot-scope="scope"> {{ scope.row.endTime | toTime }} </template>
          </el-table-column>
          <el-table-column label="持续时间">
            <template slot-scope="scope"> {{ scope.row | toDotTime }} </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :small="true"
          @size-change="handleSizeChange($event, 'Left')"
          @current-change="handleCurrentChange($event, 'Left')"
          :current-page="leftPageInfo.pageNum"
          :page-sizes="[1000, 3000]"
          :page-size="leftPageInfo.pageSize"
          layout="total,  prev, pager, next,sizes"
          :total="leftPageInfo.total"
        />
      </div>
      <div class="spin-status-inner">
        <el-table size="mini" border :data="rightData" height="calc(100% - 30px)" style="width: calc(100% - 10px)">
          <el-table-column prop="PAGE_ROW_NUMBER" label="右" width="60" align="center" />
          <!-- <el-table-column prop="mid" label="机台编号" width="150" /> -->
          <el-table-column prop="inx" label="锭号" width="50" align="center">
            <template slot-scope="scope"> {{ scope.row.inx + 1 }} </template>
          </el-table-column>
          <el-table-column prop="type" label="异常" width="150" align="center">
            <!-- <template slot-scope="scope"> {{ exceptChr[scope.row.type - 1].label }} </template> -->
          </el-table-column>

          <el-table-column prop="startTime" label="起始时间" width="106">
            <template slot-scope="scope"> {{ scope.row.startTime | toTime }} </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="106">
            <template slot-scope="scope"> {{ scope.row.endTime | toTime }} </template>
          </el-table-column>
          <el-table-column label="持续时间">
            <template slot-scope="scope"> {{ scope.row | toDotTime }} </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :small="true"
          @size-change="handleSizeChange($event, 'Right')"
          @current-change="handleCurrentChange($event, 'Right')"
          :current-page="rightPageInfo.pageNum"
          :page-sizes="[1000, 3000]"
          :page-size="rightPageInfo.pageSize"
          layout="total,  prev, pager, next,sizes"
          :total="rightPageInfo.total"
          style="width: calc(100% - 10px)"
        />
      </div>
    </div>
  </div>
</template>
<script>
import BlockTitle from '@/components/BlockTitle/index.vue'
import request from '@/utils/request'
import dayjs from 'dayjs'
var spinlist = [{ label: '全部', value: '全部' }]
for (let i = 1; i < 100; i++) {
  spinlist.push({ label: i, value: i })
}
//console.log(BlockTitle)
export default {
  name: 'Exceptional',
  components: {
    BlockTitle,
    Gap: {
      template: `<div style="width:10px"></div>`,
    },
    GapX: {
      template: `<div style="width:20px"></div>`,
    },
  },
  filters: {
    toTime(t) {
      return t ? dayjs(t).format('MM-DD HH:mm:ss') : '-'
    },

    twoNum(e) {
      return (e < 10 ? '0' : '') + e
    },
    thrNum(e) {
      return ('000' + e).slice(-3)
    },
    toDotTime(r) {
      const now = r.endTime ? dayjs(r.endTime) : dayjs()
      let t = now.diff(r.startTime, 'second')
      let timeStr = ''
      let converted = Math.floor(t / (24 * 60 * 60))
      if (converted > 0) timeStr += `${converted}天`
      t = t % (24 * 60 * 60)
      converted = Math.floor(t / (60 * 60))
      if (converted > 0) timeStr += `${converted}时`
      t = t % (60 * 60)
      converted = Math.floor(t / 60)
      if (converted > 0) timeStr += `${converted}分`
      converted = t % 60

      if (converted > 0) timeStr += `${converted}秒`
      return timeStr
    },
  },
  data() {
    return {
      except: '全部',
      timeRange: [],
      spinNum: '全部',
      spinlist,
      mid: '0000000000000000  ',
      sqlList: [
        {
          value: `select * from spin_exceptional where mid='1234567890ABCDEF' and inx = 0 order by side,inx,type,startTime `,
          label: 'all',
        },
      ],
      exceptChr: [
        // { label: '0-断头', value: 0 },
        { label: '1-超速', value: 1 },
        { label: '2-弱捻', value: 2 },
        { label: '3-断头', value: 3 },
        { label: '4-空闲', value: 4 },
        { label: '5-掉线', value: 5 },
        { label: '全部', value: '全部' },
      ],
      // exceptChr: ['0-断头', '1-掉线', '2-闲置', '3-弱捻', '4-严重弱捻', '5-锭子故障'],
      leftPageInfo: { pageSize: 1000, pageNum: 1 },
      rightPageInfo: { pageSize: 1000, pageNum: 1 },
      customColWidth: {
        id: 150,
        PackType: 80,
        Side: 60,
        SpinStartAddr: 70,
        SpinNumber: 60,
      },
      workshops: ['车间1', '车间2', '车间3'],
      macLis: [],
      macDetail: {},
      currentMac: '',
      currentWorkshop: '',
      dataList: [],
      propList: [],
      leftData: [],
      currentRow: '',
      rightData: [],
    }
  },
  computed: {},
  created() {
    const defaultSqlList = localStorage.getItem('sqlList_except')
    if (defaultSqlList) this.sqlList = JSON.parse(defaultSqlList)
    const defaultSql = localStorage.getItem('defaultSql_except')
    if (defaultSql) this.sql = this.defaultSql = defaultSql
  },
  mounted() {
    window.dj = dayjs
    //console.log(dayjs)
    this.getCurrentDateTime()
    this.getData('Left')
    this.getData('Right')
  },
  methods: {
    getCurrentDateTime() {
      // 获取当前日期时间并格式化为 yyyy-MM-dd HH:mm:ss 的格式
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')

      // 设置当前日期时间到 currentRow 变量
      this.currentRow = `${year}-${month}-${day} 00:00:00`
    },
    handleSearchBtnClick() {
      this.getData('Left')
      this.getData('Right')
    },
    async deleteFromSqlList() {
      const r = await this.$confirm('确定要移除当前sql吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      if (r != 'confirm') return
      const inx = this.sqlList.findIndex((e) => e.value == this.sql)
      if (inx > -1) {
        this.sqlList.splice(inx, 1)
        localStorage.setItem('sqlList_except', JSON.stringify(this.sqlList))
        if (this.sqlList.length > 0) {
          this.sql = this.sqlList[0].value
        }
        this.$message.info('删除完成')
      }
    },

    async addToSqlList() {
      const inx = this.sqlList.findIndex((e) => e.value == this.sql)
      if (inx > -1) return this.$message.info('该SQL已经保存过了')
      try {
        const r = await this.$prompt('请输入语句说明', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (e) => {
            return e != ''
          },
          inputErrorMessage: '不能为空',
        })

        this.sqlList.push({ value: this.sql, label: r.value })
        localStorage.setItem('sqlList_except', JSON.stringify(this.sqlList))
      } catch (e) {
        this.$message.info('你取消了')
      }
    },
    // pickerOptions: {
    //   shortcuts: [
    //     {
    //       text: '最近一周',
    //       onClick(picker) {
    //         const end = new Date()
    //         const start = new Date()
    //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    //         picker.$emit('pick', [start, end])
    //       },
    //     },
    //     {
    //       text: '最近一个月',
    //       onClick(picker) {
    //         const end = new Date()
    //         const start = new Date()
    //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    //         picker.$emit('pick', [start, end])
    //       },
    //     },
    //     {
    //       text: '最近三个月',
    //       onClick(picker) {
    //         const end = new Date()
    //         const start = new Date()
    //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
    //         picker.$emit('pick', [start, end])
    //       },
    //     },
    //   ],
    // },

    handleSelectChange(e) {
      console.log('handleSelectChange', e)
    },
    handleSizeChange(e, side) {
      console.log('handleSizeChange', e)
      if (side == 'Left') {
        this.leftPageInfo.pageSize = e
      } else {
        this.rightPageInfo.pageSize = e
      }
      this.getData(side)
    },
    handleCurrentChange(e, side) {
      if (side == 'Left') {
        this.leftPageInfo.pageNum = e
      } else {
        this.rightPageInfo.pageNum = e
      }
      this.getData(side)
    },
    async getData(side) {
      const { mid, except, timeRange, currentRow, spinNum } = this
      console.log(this.except, this.timeRange, this.spinNum)

      let sql = `select * from spin_exceptional where type <> 0 and mid='${mid}' and side='${side}' `
      sql += except != '全部' ? `and type=${except} ` : ''
      sql += spinNum != '全部' ? `and   inx = ${spinNum - 1} ` : ''
      sql += currentRow != null ? `and startTime >= '${currentRow}'` : ' '
      sql += `order by startTime DESC, inx, type `
      console.log(sql)
      const loading = this.$loading({
        lock: true,
        text: `正在加载数据`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      let pageInfo = side == 'Left' ? this.leftPageInfo : this.rightPageInfo

      try {
        const { pageNum: pagenum, pageSize: pagesize } = pageInfo
        const res = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql, pagenum, pagesize },
        })
        if (res.obj.list.length == 0) {
          this.leftData = []
          this.rightData = []
          loading.close()
          return
        }
        const {
          endRow,
          hasNextPage,
          hasPreviousPage,
          isFirstPage,
          isLastPage,
          navigateFirstPage,
          navigateLastPage,
          navigatePages,
          navigatepageNums,
          nextPage,
          pageNum,
          pageSize,
          pages,
          prePage,
          size,
          startRow,
          total,
        } = res.obj
        if (side == 'Left') {
          this.leftPageInfo = {
            endRow,
            hasNextPage,
            hasPreviousPage,
            isFirstPage,
            isLastPage,
            navigateFirstPage,
            navigateLastPage,
            navigatePages,
            navigatepageNums,
            nextPage,
            pageNum,
            pageSize,
            pages,
            prePage,
            size,
            startRow,
            total,
          }
        } else {
          this.rightPageInfo = {
            endRow,
            hasNextPage,
            hasPreviousPage,
            isFirstPage,
            isLastPage,
            navigateFirstPage,
            navigateLastPage,
            navigatePages,
            navigatepageNums,
            nextPage,
            pageNum,
            pageSize,
            pages,
            prePage,
            size,
            startRow,
            total,
          }
        }

        if (side == 'Left') {
          this.leftData = res.obj.list
          console.log('111', this.leftData)

          const typeToLabelMap = this.exceptChr.reduce((map, item) => {
            map[item.value] = item.label
            return map
          }, {})

          // 替换 this.leftData 中的 type 为对应的 label
          this.leftData = this.leftData.map((item) => ({
            type: typeToLabelMap[item.type] || item.type, // 使用映射的 label 或保留原值
            PAGE_ROW_NUMBER: item.PAGE_ROW_NUMBER,
            endTime: item.endTime,
            id: item.id,
            inx: item.inx,
            mid: item.mid,
            newsj: item.newsj,
            side: item.side,
            startTime: item.startTime,
          }))
        } else {
          this.rightData = res.obj.list
          const typeToLabelMap = this.exceptChr.reduce((map, item) => {
            map[item.value] = item.label
            return map
          }, {})

          // 替换 this.leftData 中的 type 为对应的 label
          this.rightData = this.rightData.map((item) => ({
            type: typeToLabelMap[item.type] || item.type, // 使用映射的 label 或保留原值
            PAGE_ROW_NUMBER: item.PAGE_ROW_NUMBER,
            endTime: item.endTime,
            id: item.id,
            inx: item.inx,
            mid: item.mid,
            newsj: item.newsj,
            side: item.side,
            startTime: item.startTime,
          }))
        }
      } catch (e) {
        console.log('Error:', e)
      } finally {
        loading.close()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~@/styles/variables.scss';

.page-wrap {
  padding: 10px 20px;
  box-sizing: border-box;
}

.sub-item {
  width: 44px;
  text-align: center;
  border-right: 1px #eee solid;
  flex-shrink: 0;
}

.top-wrap {
  width: 800px;
  display: flex;
  align-items: center;
  font-size: 12px;
}

.spin-status {
  margin-top: 10px;
  height: calc(100vh - 170px);
  display: flex;
}

.spin-status-inner {
  width: 50%;
}

.spin-list-row {
  // border-left: 1px solid #eee;
  // border-right: 1px solid #eee;
  display: flex;
}

.spin-list-col {
  width: 4%;
  height: 40px;
  padding: 4px;
  box-sizing: border-box;
}

.spin-list-item {
  width: 100%;
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  display: flex;
  font-size: 12px;
  align-items: center;
  justify-content: center;
}

.spin-list-title {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  letter-spacing: 1px;
}

::v-deep .el-select .el-select-dropdown .el-scrollbar {
  padding-bottom: 15px !important;
}
</style>
